/**
  ******************************************************************************
  * @file    main.c 
  * @author  lyjliyuan@sina.com
  * @version V0.1
  * @date    08-agaust-2018
  * @brief   Main program body
  */  

/* Includes ------------------------------------------------------------------*/
#include "stm32f10x.h"
#include "nixie_tube.h"
#include "uart_com.h"
#include "mytype.h"
#include "protocol.h"
#include "aip1628.h"
#include <stdio.h>


#define KEY_IRQ_PIN (GPIO_Pin_5 | GPIO_Pin_6)

volatile FLASH_Status FLASHStatus = FLASH_COMPLETE;


/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/

/* Private function prototypes -----------------------------------------------*/
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
   set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */

unsigned char recvdata[20];
uint16   g_board_ID = 0;
extern unsigned char key_flag;
extern int irq_cnt;
void medey(int ms)
{
   int i,j;
	 for (i=0;i<ms;i++) {
	    for(j=0;j<1000;j++);
	 }

}

void led_show(void)
{
		GPIO_SetBits(GPIOA, GPIO_Pin_11);
		medey(100);
		GPIO_ResetBits(GPIOA, GPIO_Pin_11);
		medey(100);

}

void NVIC_init(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;   
  
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
//| USART1_IRQn
  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn ;     //
  //NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;         //
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;                //
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;                   //
  NVIC_Init(&NVIC_InitStructure);
  
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);       
//| USART2_IRQn
  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn ;     //
  //NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;         //
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;                //
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;                   //
  NVIC_Init(&NVIC_InitStructure);  
	
	  /* Enable and set PA8 gpio irq EXTI9_5 Interrupt to the lowest priority */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);	
}

void NVIC_deinit(void)
{
  NVIC_InitTypeDef NVIC_InitStructure;   
  
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
//| USART1_IRQn
  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn ;     //
  //NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;         //
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;                //
  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;                   //
  NVIC_Init(&NVIC_InitStructure);
  
  NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);       
//| USART2_IRQn
  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn ;     //
  //NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;         //
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;                //
  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;                   //
  NVIC_Init(&NVIC_InitStructure);  
	
	  /* Enable and set PA8 gpio irq EXTI9_5 Interrupt to the lowest priority */
  NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;
  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
  NVIC_Init(&NVIC_InitStructure);	
}

void led_key_init(void)
{
	GPIO_InitTypeDef   GPIO_InitStructure;
  EXTI_InitTypeDef   EXTI_InitStructure;
	
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

  /* Configure PA11 and PA12 in output OD mode led*/
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
  /* Configure PA.5.6 pin as input floating */
  GPIO_InitStructure.GPIO_Pin = KEY_IRQ_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
	  /* Connect EXTI8 Line to PA.00 pin */
  GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource5);
  EXTI_ClearITPendingBit(EXTI_Line5);
  /* Configure EXTI8 line */
  EXTI_InitStructure.EXTI_Line = EXTI_Line5;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;  
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);
	
	  GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource6);
  EXTI_ClearITPendingBit(EXTI_Line6);
  /* Configure EXTI8 line */
  EXTI_InitStructure.EXTI_Line = EXTI_Line6;
  EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
  EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;  
  EXTI_InitStructure.EXTI_LineCmd = ENABLE;
  EXTI_Init(&EXTI_InitStructure);

}

void TIM3_Int_Init(u16 arr,u16 psc)
{
  TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
 
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能
	
	//定时器TIM3初始化
	TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值	
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置用来作为TIMx时钟频率除数的预分频值
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; 
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  //TIM向上计数模式
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
 

 
	//中断优先级NVIC设置
	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; 
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; 
	NVIC_Init(&NVIC_InitStructure);  //初始化NVIC寄存器
 
 
	TIM_Cmd(TIM3, ENABLE);  //使能TIM3		
  TIM_ClearITPendingBit(TIM3, TIM_IT_Update  ); 	
	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //使能指定的TIM3中断，允许更新中断
}

void TIM3_Int_DeInit()
{
	NVIC_InitTypeDef NVIC_InitStructure;
 
	//中断优先级NVIC设置
	NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; 
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  
	NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE; 
	NVIC_Init(&NVIC_InitStructure);  //初始化NVIC寄存器

  TIM_ClearITPendingBit(TIM3, TIM_IT_Update  ); 	
	TIM_ITConfig(TIM3,TIM_IT_Update,DISABLE ); //
	TIM_Cmd(TIM3, DISABLE);  //	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, DISABLE); //时钟使能
}

int Read_OldID_NBtye(uint32_t ReadAddress, uint8_t *ReadBuf, int32_t ReadNum) 
{        
    int DataNum = 0;		
	ReadAddress = (uint32_t)STARTADDR + ReadAddress;         
	while(DataNum < ReadNum) 		{           
	*(ReadBuf + DataNum) = *(__IO uint8_t*) ReadAddress++;           
	DataNum++;        }        
	return DataNum;
} 

int ReadFlashNBtye(uint32_t ReadAddress, uint8_t *ReadBuf, int32_t ReadNum) 
{        
    int DataNum = 0;		
	ReadAddress = (uint32_t)SCREEN_ID_ADDR + ReadAddress;         
	while(DataNum < ReadNum) 		{           
	*(ReadBuf + DataNum) = *(__IO uint8_t*) ReadAddress++;           
	DataNum++;        }        
	return DataNum;
	
} 

void WriteFlashOneWord(uint32_t WriteAddress,uint32_t WriteData)
{	
	FLASH_UnlockBank1();	
	FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);     
	FLASHStatus = FLASH_ErasePage(SCREEN_ID_ADDR); 	
	if(FLASHStatus == FLASH_COMPLETE)	{		
	FLASHStatus = FLASH_ProgramWord(SCREEN_ID_ADDR + WriteAddress, WriteData);    //flash.c 中API函数		
//	FLASHStatus = FLASH_ProgramWord(SCREEN_ID_ADDR + WriteAddress+4, arrow);                     
	//需要写入更多数据时开启		
	//FLASHStatus = FLASH_ProgramWord(SCREEN_ID_ADDR+8, 0x87650000);                     
	//需要写入更多数据时开启	
	}	
	FLASH_LockBank1();
}

void ApplicationJumpToBoot(uint32  app_address)
{
    pFunction JumpToApplication;
    uint32 JumpAddress;
    
    if (((*(__IO uint32*)app_address) & 0x2FFE0000 ) == 0x20000000)
    {
      /* Jump to user application */
      JumpAddress = *(__IO uint32*) (app_address + 4);
      JumpToApplication = (pFunction) JumpAddress;
      /* Initialize user application's Stack Pointer */
      __set_MSP(*(__IO uint32*) app_address);
      JumpToApplication();
    }
}
void app_deinit()
{
	NVIC_deinit();
	Tm1628_ClearDisplay();
	uart_com1_deinit();
	uart_com2_deinit();
	TIM3_Int_DeInit();
	  GPIOA->CRL = 0X44444444;
    GPIOA->CRH = 0X44444444;
    GPIOA->ODR = 0X00000000;
    GPIOB->CRL = 0X44444444;
    GPIOB->CRH = 0X44444444;
    GPIOB->ODR = 0X00000000;
    //clk uart2 
    RCC->APB1ENR = 0x00000000;
    //clk uart1 GPIOA GPIOB GPIOC
    RCC->APB2ENR = 0x00000000;
	
}
/* Private functions ---------------------------------------------------------*/

/**
  * @brief  Main program.
  * @param  None
  * @retval None
  */
int main(void)
{
	int readnum=0;
	uint8_t Temp_Data[20] = {0};
	int i,k=0;
	int key_state_pre = 0xFF;
	int key_state_cur = 0xFF;
	uint8_t oldID_buf[10] = {0};
	uint16_t ID=0;
  /* GPIOA Periph clock enable */
	//led gpio init
 // SCB->VTOR = FLASH_BASE | FLASH_VTOR_OFFSET;
	
  led_key_init();
	//nixie tube gpio init
  //nixie_tube_gpio_init();
	queue_init();
	medey(30);
	//GPIO_SetBits(GPIOB, TUBE_SEGMENT_CHOOSE_A1 | TUBE_SEGMENT_CHOOSE_A2 | TUBE_SEGMENT_CHOOSE_A3 | TUBE_SEGMENT_CHOOSE_A4);
  //nixie_tube_show_one(1);

  uart_com1_init();
	uart_com2_init();
  NVIC_init();
	//readnum = ReadFlashNBtye(0, Temp_Data,4); //读取数据
	UART_485_RX_CTRL;
	
	Tm1628init();

	Read_OldID_NBtye(0,oldID_buf,4);
  ID = oldID_buf[0] | (oldID_buf[1] <<8);
	show_num(ID);
	medey(3000);
	if(0 < ID && ID < 240) {
		WriteFlashOneWord(0,ID);
		medey(1000);
	}
	show_num(8888);
	medey(3000);
	g_board_ID = ReadFlashNBtye(0, Temp_Data,4); //读取数据
	g_board_ID = Temp_Data[0] | (Temp_Data[1]<<8);
	g_arrow_direction = Temp_Data[2];

	//show_arrow();
	//Tout（溢出时间）=（ARR+1)(PSC+1)/Tclk  72M 这个4999就是500ms
//	TIM3_Int_Init(4999,7199);
	show_num(g_board_ID);
	medey(2000);
//show_num(g_arrow_direction);
  /* Infinite loop */
  while (1)
  {
		/*write ID only once*/
		if (flag_wr_flash) {
			  flag_wr_flash = 0;
				WriteFlashOneWord(0,g_flash_ID);
			uart_send_data(USART1, g_flash_ID);
		}
		if (g_show_ID) {
			  g_show_ID = 0;
				show_num(g_board_ID);
			uart_send_data(USART1, g_board_ID);
		}
		readnum = ReadFlashNBtye(0, Temp_Data,4); //读取数据
	  g_board_ID = Temp_Data[0] | (Temp_Data[1]<<8);
		
		if (g_pre_show_number) {
			g_pre_show_number = 0;
			show_num(g_show_number);
			//uart_send_data(USART1, g_show_number);
		}
		
		if(g_byteRxComBuf.Length > 50 && k==0) {
				for(i=0;i<g_byteRxComBuf.Length;i++) {
				uart_send_data(USART1,g_byteRxComBuf.pbuf[(g_byteRxComBuf.Head+i )]);
		    }
		k=1;
		}
		DecMsg(&g_byteRxComBuf , MSGSIZE);
    //uart_send_data(USART1, Temp_Data[3]);
   // uart_send_data(USART1, 0x22);
		//uart_send_data(USART1, Temp_Data[1]);
		//uart_send_data(USART1, Temp_Data[0]);
		//uart_send_data(USART2, 0x00);
		//uart_send_data(USART2, 0xaa);
		//uart_send_data(USART2, 0x55);
		//uart_send_data(USART2, 0x66);
		//key down show history
		key_state_cur = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_6);
		if(key_state_cur == Bit_RESET && key_state_cur != key_state_pre) {
			if(g_show_number != 0) {
						show_num(g_show_number);
				} else {
						show_line_noorder();
			}
			
		}else if(key_state_cur == Bit_SET && key_state_cur != key_state_pre){
			Tm1628_ClearDisplay();
		}
		/*if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) == Bit_RESET && GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) != key_state_pre ){
			medey(10);
			if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) == Bit_RESET) {
				if(g_show_number != 0) {
						show_num(g_show_number);
					show_num(5000+irq_cnt);
				} else {
						show_line_noorder();
					show_num(irq_cnt);
				}
			 key_state_pre = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5);
			}
    } else 
		if((GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) == Bit_SET && GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) != key_state_pre)
		){
			medey(10);
			if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5) == Bit_SET) {
				Tm1628_ClearDisplay();
			}
	   key_state_pre = GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5);
		}*/
	 key_state_pre = key_state_cur;
  }

}
/**
  * @brief  Retargets the C library printf function to the USART.
  * @param  None
  * @retval None

PUTCHAR_PROTOTYPE
{

  USART_SendData(EVAL_COM1, (uint8_t) ch);

  while (USART_GetFlagStatus(EVAL_COM1, USART_FLAG_TC) == RESET)
  {}

  return ch;
}
*/
#ifdef  USE_FULL_ASSERT
void assert_failed(uint8_t* file, uint32_t line)
{ 
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif

/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
